package com.itheima.website.filter;

/**
 * 这个参数过滤器,直接帮助我们进行参数封装,如果有实体类即可
 */

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.website.domain.User;
import com.itheima.website.utils.BeanFactory;

/**
 * Servlet Filter implementation class ParameterFilter
 */
public class ParameterFilter implements Filter {

    /**
     * Default constructor. 
     */
    public ParameterFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//获取request或者response
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		//获取参数
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		//对象封装
		//通过配置文件获取
		User user = null;
		try {
			String path = req.getSession().getServletContext().getRealPath("WEB-INF/classes/website.xml");
			Object obj = BeanFactory.createBean("user",path);
			user = (User) BeanFactory.propertyIntoObject(obj, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(user);
		req.getSession().setAttribute("user", user);
	
		chain.doFilter(req, res);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	


}
